<?php
/**
 * version 1.0.0
 * 自定义助手函数
 * 检查是否定义，避免冲突 if(!function_exists('function_test'))
 */
use App\common\models\Setting;
use Illuminate\Support\Facades\Cache;

/**
 * @param $content
 * @param $level string
 */
if (!function_exists('writeLog')) {
    function writeLog($name, $content, $level) {
        //创建日志文件
        $log_file = createLogFile();
        //组合日志内容
        $message = contentFormat($name, $content, $level);
        //写入日志
        file_put_contents($log_file, $message."\r\n", FILE_APPEND );
    }
}

/**
 * 创建日志文件
 */
if (!function_exists('createLogFile')) {
    function createLogFile(){
        $path = storage_path()."/logs/".date('Ymd')."/";
        $fileName = "error_".date("Y-m-d").'.log';
        //创建日志目录
        if(!file_exists($path)){
            mkdir($path,0777,true);
        }
        //创建日志文件
        if(!file_exists($path.$fileName)){
            fopen($path.$fileName,'a');
        }
        return $path.$fileName;
    }
}

/**
 * 格式化日志内容
 * @param $content
 * @param $level
 * @return string
 */
if (!function_exists('contentFormat')) {
    function contentFormat($name, $content, $level){
        switch ($level){
            case 1:
                $message['level'] = "error";
                break;
            case 2:
                $message['level'] = "warning";
                break;
            case 3:
                $message['level'] = "info";
                break;
            case 4:
                $message['level'] = "trace";
                break;
        }
        $message['name'] = $name;
        $message['content'] = $content;
        $message['time'] = date("Y-m-d H:i:s", time());
        return json_encode($message,500);
    }
}

/**
 * 日志错误级别：错误
 */
if (!function_exists('ERROR')) {
    function ERROR($content){
        $log_file = createLogFile();
        $message = contentFormat($content,1);
        file_put_contents($log_file, $message."\r\n", FILE_APPEND );
    }
}

/**
 * 日志错误级别：警告
 */
if (!function_exists('WARNING')) {
    function WARNING($content){
        $log_file = createLogFile();
        $message = contentFormat($content,2);
        file_put_contents($log_file, $message, FILE_APPEND );
    }
}

/**
 * 日志错误级别：信息
 */
if (!function_exists('INFO')) {
    function INFO($content){
        $log_file = createLogFile();
        $message = contentFormat($content,3);
        file_put_contents($log_file, $message."\r\n", FILE_APPEND );
    }
}

/**
 * 日志错误级别：追踪
 */
if (!function_exists('TRACE')) {
    function TRACE($content){
        $log_file = createLogFile();
        $message = contentFormat($content,4);
        file_put_contents($log_file, $message."\r\n", FILE_APPEND );
    }
}

/**
 * 测试助手函数
 * @data array
 */
if (!function_exists('function_test')) {
    function function_test() {
        return 'hello world';
    }
}

/**
 * 接口返回成功 JSON格式
 * @param string $message 提示信息
 * @param array $data 返回数据
 * @return \Illuminate\Http\JsonResponse
 */
if (!function_exists('successJson')) {
    function successJson($message = '成功', $data = []) {
        return response()->json([
            'code' => 200,
            'msg' => $message,
            'data' => $data
        ], 200, ['charset' => 'utf-8']);
    }
}

/**
 * 接口返回错误JSON 格式
 * @param string $message 提示信息
 * @param array $data 返回数据
 * @return \Illuminate\Http\JsonResponse
 */
if (!function_exists('errorJson')) {
    function errorJson($message = '失败', $data = []) {
        return response()->json([
            'code' => 0,
            'msg' => $message,
            'data' => $data
        ], 200, ['charset' => 'utf-8']);
    }
}

/**
 * 接口返回错误json_encode格式
 * @param string $message 提示信息
 * @param array $data 返回数据
 * @return \Illuminate\Http\JsonResponse
 */
if (!function_exists('jsonEncode')) {
    function jsonEncode($message = '获取信息失败', $data = []) {
        echo json_encode([
            'code' => 0,
            'msg' => $message,
            'data' => $data
        ]);
        exit;
    }
}


/**
 * 格式化时间
 * @desc 将时间戳格式化为日期格式
 */
if (!function_exists('getFormatTime')) {
    function getFormatTime($time,$type=0)
    {
        switch ($type){
            case 1:
                $date = date('Y-m-d H:i',$time);
                break;
            case 2:
                $date = date('Y-m-d',$time);
                break;
            case 3:
                $date = date('Y-m',$time);
                break;
            default:
                $date = date('Y-m-d H:i:s',$time);
                break;
        }
        return $date;
    }
}

/**
 * 获取时间格式
 */
if (!function_exists('iotGetDay')) {
    function getDay($type = 1)
    {
        if ($type == 2) {
            return date('Y-m-d');
        } else {
            return date('Y-m-d H:i:s');
        }
    }
}

/**
 * 获取全局settings缓存
 */
if (!function_exists('cacheGlobalSettings')) {
    function cacheGlobalSettings()
    {

        if (Cache::has('settings')) {
            return Cache::get('settings');
        }
        $settings = Setting::all();


        if ($settings) {
            $settings = $settings->toArray();
            foreach ($settings as $key => $value) {
                $all_setting[$value['key']] = $value;
            }
            Cache::put('settings', $all_setting, 5);
        }

        return Cache::get('settings');

    }
}

/**
 * 获取全局settings缓存通过key
 */
if (!function_exists('cacheGlobalSettingsByKey')) {
    function cacheGlobalSettingsByKey($key, $field = "value")
    {

        return Cache::get('settings')[$key][$field];

    }
}

/**
 * 获取全局settings缓存通过key
 */
if (!function_exists('__E')){
    function __E($key, $field = "value") {
        if (!isset(Cache::get('settings')[$key])) {
            // by andy update 这里用之前的会一直报错  缓存不存在 重新获取
            $cache = Setting::where('key', $key)->first();
            //throw new \Exception("缓存" . $key . "不存在!");
            if (empty($cache)) throw new \Exception("缓存" . $key . "不存在!");
            return empty($cache[$field]) ? '' : $cache[$field];
        }
        $cache = Cache::get('settings')[$key];
        return empty($cache[$field]) ? '' : $cache[$field];
    }
}

/**
 * 验证是否为手机号码
 */
if (!function_exists('is_mobile')) {
    function is_mobile(string $text) {
        $search = '/^0?1[3|4|5|6|7|8][0-9]\d{8}$/';
        if (preg_match($search, $text)) return true;
        else return false;
    }
}

/**
 * 手机号码 中间4位加密
 */
if (!function_exists('get_encryption_mobile')) {
    function get_encryption_mobile($tel) {
        $new_tel = preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $tel);
        return $new_tel;
    }
}

/**
 * 检测邮件格式
 */
if (!function_exists('checkEmail')) {
    function checkEmail($email_adress) {

        $pattern = '/^[a-z0-9]+([._-][a-z0-9]+)*@([0-9a-z]+\.[a-z]{2,14}(\.[a-z]{2})?)$/i';

        if (preg_match($pattern, $email_adress)) return true;
        else return false;
    }
}

/**
 * 随机验证码
 */
if (!function_exists('random_verification_code')) {
    function random_verification_code($length = 6) {
        $code = '';
        for ($i = 0; $i < $length; $i++) $code .= mt_rand(0, 9);
        return $code;
    }
}

/**
 * 获取随机字符串
 * @param number $length 字符串长度
 * @param boolean $numeric 是否为纯数字
 * @return string
 */
if (!function_exists('random')) {
    function random($length, $numeric = FALSE) {
        $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
        $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
        if ($numeric) {
            $hash = '';
        } else {
            $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
            $length--;
        }
        $max = strlen($seed) - 1;
        for ($i = 0; $i < $length; $i++) {
            $hash .= $seed[mt_rand(0, $max)];
        }
        return $hash;
    }
}

/**
 * 获取IP与浏览器信息、语言
 */
if (!function_exists('get_client_info')) {
    function get_client_info(): array {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $XFF = $_SERVER['HTTP_X_FORWARDED_FOR'];
            $client_pos = strpos($XFF, ', ');
            $client_ip = false !== $client_pos ? substr($XFF, 0, $client_pos) : $XFF;
            unset($XFF, $client_pos);
        } else $client_ip = $_SERVER['HTTP_CLIENT_IP'] ?? $_SERVER['REMOTE_ADDR'] ?? $_SERVER['LOCAL_ADDR'] ?? '0.0.0.0';
        $client_lang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 5) : '';
        $client_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
        return ['ip' => &$client_ip, 'lang' => &$client_lang, 'agent' => &$client_agent];
    }
}

/**
 * 获取用户IP
 */
if (!function_exists('get_ip')) {
    function get_ip(): string {
        $data = get_client_info();
        return empty($data['ip']) ? '' : $data['ip'];
    }
}

/**
 * 获取当前host域名
 */
if (!function_exists('get_host')) {
    function get_host()
    {
        $scheme = empty($_SERVER['HTTPS']) ? 'http://' : 'https://';
        $url = $scheme . $_SERVER['HTTP_HOST'] . '/';
        return $url;
    }
}

/**
 * 生成邀请码函数
 * 注意这里生成的邀请码 不会超过 13位数 超过13 位函数递归
 * 后期业务量大可以重新改进
 * 参数id 为数据库自增id
 * 数据库自增id 大于100 万请重新改进和使用其他方法
 */
if (!function_exists('createOnlyId')) {
    function createOnlyId($id)
    {

        //打乱字符串种子
        $code = str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZksdjfksdjwieujqoznnqweurjajdjskjdkfjdsfkslcxvio');

        $rand = $code[rand(0, 25)]
            . strtoupper(dechex(date('m')))
            . date('d')
            . substr(time(), -5)
            . substr(microtime(), 2, 5)
            . sprintf('%02d', rand(0, 99));
        for (
            $a = md5($rand, true),
            $s = str_shuffle('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZaloqweoernxzmvnxmvmxcskafhksddqellmkjajdffd'),
            $d = '',
            $f = 0;
            $f < 4;
            $g = ord($a[$f]),
            $d .= $s[($g ^ ord($a[$f + 8])) - $g & 0x1F],
            $f++
        ) ;

        //将id 放入数组 这样可以放头部跟尾部，不一样
        $arr = [0 => rand(0, 10), 1 => $id, 2 => date('s'), 3 => date('i')];

        //将id 唯一值 $arr[1] 加入进去
        $re_str = $arr[rand(0, 3)] . $d . $arr[1];
        //位数大于13 重新生成 函数递归
        if (strlen($re_str) > 13) {
            return createOnlyId($id);
        } else {
            return $re_str;
        }

    }
}

/**
 * 判断是否是微信浏览器
 */
if (!function_exists('is_weixin')) {
    function is_weixin()
    {

        if (strpos($_SERVER['HTTP_USER_AGENT'],
                'MicroMessenger') !== false) {
            return true;
        }
        return false;

    }
}

/**
 * 循环创建目录
 */
if (!function_exists('mk_dir')) {
    function mk_dir($dir, $mode = 0755)
    {
        if (is_dir($dir) || @mkdir($dir, $mode)) return true;
        if (!mk_dir(dirname($dir), $mode)) return false;
        return @mkdir($dir, $mode);
    }
}

/**
 * 过滤值为空的数组
 */
if (!function_exists('filterEmptyArr')) {
    function filterEmptyArr($array)
    {

        if (!is_array($array)) return false;

        $return_arr = array();
        foreach ($array as $k => $v) {
            if (is_array($v)) {

                foreach ($v as $k1 => $v1) {
                    if ($v1) {
                        $return_arr[$k] = $v;
                    }
                }

            } else if ($v) {
                $return_arr[$k] = $v;
            }


        }

        return $return_arr;
    }
}

/**
 * 验证数组是否为空,除了指定的key
 */
if (!function_exists('CheckArrIsEmpty')) {
    function CheckArrIsEmpty($arr, $except = [])
    {
        if (!is_array($arr)) return false;
        foreach ($arr as $k => $value) {
            if (is_array($value)) {
                CheckArrIsEmpty($value);
            } else if (!$value && $value != 0) {
                if (!in_array($k, $except)) {
                    throw  new  Exception($k . " is empty.", 40000);
                }
            }
        }
    }
}

/**
 * 获取客户端浏览器信息
 */
if (!function_exists('get_broswer')) {
    function get_broswer()
    {
        $sys = $_SERVER['HTTP_USER_AGENT'];  //获取用户代理字符串
        if (stripos($sys, "Firefox/") > 0) {
            preg_match("/Firefox\/([^;)]+)+/i", $sys, $b);
            $exp[0] = "Firefox";
            $exp[1] = $b[1];    //获取火狐浏览器的版本号
        } elseif (stripos($sys, "Maxthon") > 0) {
            preg_match("/Maxthon\/([\d\.]+)/", $sys, $aoyou);
            $exp[0] = "傲游";
            $exp[1] = $aoyou[1];
        } elseif (stripos($sys, "MSIE") > 0) {
            preg_match("/MSIE\s+([^;)]+)+/i", $sys, $ie);
            $exp[0] = "IE";
            $exp[1] = $ie[1];  //获取IE的版本号
        } elseif (stripos($sys, "OPR") > 0) {
            preg_match("/OPR\/([\d\.]+)/", $sys, $opera);
            $exp[0] = "Opera";
            $exp[1] = $opera[1];
        } elseif (stripos($sys, "Edge") > 0) {
            //win10 Edge浏览器 添加了chrome内核标记 在判断Chrome之前匹配
            preg_match("/Edge\/([\d\.]+)/", $sys, $Edge);
            $exp[0] = "Edge";
            $exp[1] = $Edge[1];
        } elseif (stripos($sys, "Chrome") > 0) {
            preg_match("/Chrome\/([\d\.]+)/", $sys, $google);
            $exp[0] = "Chrome";
            $exp[1] = $google[1];  //获取google chrome的版本号
        } elseif (stripos($sys, 'rv:') > 0 && stripos($sys, 'Gecko') > 0) {
            preg_match("/rv:([\d\.]+)/", $sys, $IE);
            $exp[0] = "IE";
            $exp[1] = $IE[1];
        } else {
            $exp[0] = "未知浏览器";
            $exp[1] = "";
        }
        return $exp[0] . '(' . $exp[1] . ')';
    }
}

/**
 * 获取客户端操作系统信息,包括win10
 */
if (!function_exists('get_os')) {
    function get_os()
    {

        $agent = $_SERVER['HTTP_USER_AGENT'];
        $os = false;

        if (preg_match('/win/i', $agent) && strpos($agent, '95')) {
            $os = 'Windows 95';
        } else if (preg_match('/win 9x/i', $agent) && strpos($agent, '4.90')) {
            $os = 'Windows ME';
        } else if (preg_match('/win/i', $agent) && preg_match('/98/i', $agent)) {
            $os = 'Windows 98';
        } else if (preg_match('/win/i', $agent) && preg_match('/nt 6.0/i', $agent)) {
            $os = 'Windows Vista';
        } else if (preg_match('/win/i', $agent) && preg_match('/nt 6.1/i', $agent)) {
            $os = 'Windows 7';
        } else if (preg_match('/win/i', $agent) && preg_match('/nt 6.2/i', $agent)) {
            $os = 'Windows 8';
        } else if (preg_match('/win/i', $agent) && preg_match('/nt 10.0/i', $agent)) {
            $os = 'Windows 10';#添加win10判断
        } else if (preg_match('/win/i', $agent) && preg_match('/nt 5.1/i', $agent)) {
            $os = 'Windows XP';
        } else if (preg_match('/win/i', $agent) && preg_match('/nt 5/i', $agent)) {
            $os = 'Windows 2000';
        } else if (preg_match('/win/i', $agent) && preg_match('/nt/i', $agent)) {
            $os = 'Windows NT';
        } else if (preg_match('/win/i', $agent) && preg_match('/32/i', $agent)) {
            $os = 'Windows 32';
        } else if (preg_match('/linux/i', $agent)) {
            $os = 'Linux';
        } else if (preg_match('/unix/i', $agent)) {
            $os = 'Unix';
        } else if (preg_match('/sun/i', $agent) && preg_match('/os/i', $agent)) {
            $os = 'SunOS';
        } else if (preg_match('/ibm/i', $agent) && preg_match('/os/i', $agent)) {
            $os = 'IBM OS/2';
        } else if (preg_match('/Mac/i', $agent) && preg_match('/PC/i', $agent)) {
            $os = 'Macintosh';
        } else if (preg_match('/PowerPC/i', $agent)) {
            $os = 'PowerPC';
        } else if (preg_match('/AIX/i', $agent)) {
            $os = 'AIX';
        } else if (preg_match('/HPUX/i', $agent)) {
            $os = 'HPUX';
        } else if (preg_match('/NetBSD/i', $agent)) {
            $os = 'NetBSD';
        } else if (preg_match('/BSD/i', $agent)) {
            $os = 'BSD';
        } else if (preg_match('/OSF1/i', $agent)) {
            $os = 'OSF1';
        } else if (preg_match('/IRIX/i', $agent)) {
            $os = 'IRIX';
        } else if (preg_match('/FreeBSD/i', $agent)) {
            $os = 'FreeBSD';
        } else if (preg_match('/teleport/i', $agent)) {
            $os = 'teleport';
        } else if (preg_match('/flashget/i', $agent)) {
            $os = 'flashget';
        } else if (preg_match('/webzip/i', $agent)) {
            $os = 'webzip';
        } else if (preg_match('/offline/i', $agent)) {
            $os = 'offline';
        } else {
            $os = '未知操作系统';
        }
        return $os;
    }
}

/**
 * 上传单文件
 */
if (!function_exists('UploadFile')) {
    function UploadFile($request,
                        $field,
                        $filename,
                        $allowExt = ALLOWEXT,
                        $drive = "local",
                        $preview = null,
                        $preview_w = 0,
                        $preview_h = 0,
                        $watermark_type = null,
                        $watermark_text = "",
                        $preview_watermark = null,
                        $watermark = null
    )
    {

        //判断是否开启文件上传功能
        if (__E("upload_status") == 0) {
            throw new Exception("系统没有开启上传功能！", 40000);
        }

        //判断文件大小
        if ($_FILES[$field]['size'] <= 0) {

            throw new Exception("文件没有选择！", 40000);

        } else {

            //判断文件大小
            if ($_FILES[$field]['size'] / 1024 > __E("upload_limit")) {
                throw new Exception("超出文件设置大小！", 40000);
            }

            //判断文件格式
            $file = $request->file($field);
            //获取文件的扩展名
            $ext = $file->getClientOriginalExtension();
            $ext = strtolower($ext);
            //过滤文件格式
            if (!in_array($ext, explode(",", $allowExt))) {
                throw new Exception("文件格式不允许！", 40000);
            }
        }

        switch (__E("upload_driver")) {

            case "local":

                return _upload($request, $field, $filename, $allowExt, $drive, true, $preview, $preview_w, $preview_h, $watermark_type, $watermark_text, $preview_watermark, $watermark);

                break;


            default :

                //判断插件是否存在
                if (is_dir(PLUGIN_PATH_FILE . __E("upload_driver"))) {

                    //触发上传驱动事件

                    $filename = event(new \App\Events\UploadDriver($request, $field, $filename, $allowExt, $drive, "put"));

                    return $filename[0];

                } else {

                    throw new Exception("Upload driver does not exist！", 40000);

                }

                break;


        }


    }
}

/**
 * 上传图片
 */
if (!function_exists('_upload')) {
    function _upload($request,
                     $field,
                     $filename,
                     $allowExt,
                     $drive,
                     $addAttachment = true,
                     $preview = null,
                     $preview_w = 0,
                     $preview_h = 0,
                     $watermark_type = null,
                     $watermark_text = "",
                     $preview_watermark = null,
                     $watermark = null
    )
    {
        if ($_FILES[$field]['size'] <= 0) {
            return false;
        }
        $file = $request->file($field);
        if ($file->isValid()) { //括号里面的是必须加的哦
            //如果括号里面的不加上的话，下面的方法也无法调用的
            //获取文件的扩展名
            $ext = $file->getClientOriginalExtension();
            //获取文件的绝对路径
            $path = $file->getRealPath();

            //定义文件名
            $filename = $filename . '.' . $ext;

            //存储文件。disk里面的public。总的来说，就是调用disk模块里的public配置
            Storage::disk($drive)->put($filename, file_get_contents($path));

            if ($preview) {
                //定义预览名称,设置裁剪图片保存的名称
                $pre_filename = public_path() . "/" . 'uploads' . "/" . "preview" . "/" . $filename;
                if (!is_dir(dirname($pre_filename))) {
                    mk_dir(dirname($pre_filename), 0777);
                }
                try {
                    //缩略图
                    $image = \Intervention\Image\Facades\Image::make(public_path() . "/" . 'uploads' . "/" . $filename);
                    if ($preview_w && $preview_h) {
                        $image->height($preview_h);
                        $image->width($preview_w);
                    } else if ($preview_w) {
                        $image->widen($preview_w);
                    } else if ($preview_h) {
                        $image->heighten($preview_h);
                    }
                    if ($preview_watermark) {
                        if ($watermark_type == "img") {
                            $image->insert(GetUrlByPath(__E("watermark_img")), __E("watermark_position"), 10, 10);
                        } else if ($watermark_type == "text") {
                            $image->text($watermark_text, 20, 20, function ($font) {
                                $font->file(public_path() . '/xkb.ttf');
                                $font->size(__E("watermark_text_size"));
                                $font->color(__E("watermark_text_color"));
//                        $font->align('center');
                                $font->valign('top');
                                $font->angle(__E("watermark_text_angle"));
                            });
                        }
                    }
                    $image->save($pre_filename);

                    //原图
                    if ($watermark) {
                        $image2 = \Intervention\Image\Facades\Image::make(public_path() . "/" . 'uploads' . "/" . $filename);
                        if ($watermark_type == "img") {
                            $image2->insert(GetUrlByPath(__E("watermark_img")), __E("watermark_position"), 10, 10);
                        } else if ($watermark_type == "text") {
                            $image2->text($watermark_text, 20, 20, function ($font) {
                                $font->file(public_path() . '/xkb.ttf');
                                $font->size(__E("watermark_text_size"));
                                $font->color(__E("watermark_text_color"));
//                        $font->align('center');
                                $font->valign('top');
                                $font->angle(__E("watermark_text_angle"));
                            });
                        }
                        $image2->save(public_path() . "/" . 'uploads' . "/" . $filename);
                    }

                } catch (Exception $exception) {
                    throw new \Exception($exception->getMessage());
                }
            }

            //添加到附件表
            if ($addAttachment) {
                addAttachment($filename, $drive);
                if ($pre_filename) {
                    addAttachment("preview" . "/" . $filename, $drive);
                }
            }

            return $filename;
        }
    }
}

/**
 * 生成树形结构数据
 */
if (!function_exists('listToTree')){
    function listToTree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0) {
        $tree = array();
        if (is_array($list)) {
            $refer = array();
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] = &$list[$key];
            }

            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId = $data[$pid];

                if ($root == $parentId) {
                    $tree[$data[$pk]] = &$list[$key];
                } else {
                    if (isset($refer[$parentId])) {
                        $parent = &$refer[$parentId];
                        $parent[$child][$data[$pk]] = &$list[$key];
                    }
                }
            }
        }

        return $tree;
    }
}

/**
 * 读取树形数据,树形数据$data，$pid 当前菜单的父ID
 */
if (!function_exists('getTreeData')) {
    function getTreeData($data, $pid = 0)
    {

        foreach ($data as $key => $val) {

            if ($pid == $val["id"]) {
                $select = " selected ";
            } else {
                $select = "  ";
            }

            echo "<option value='" . $val["id"] . "' " . $select . " >" . cerate_xxx($val["level"]) . $val["name"] . "</option>";

            if (isset($val["sub"])) {
                getTreeData($val["sub"], $pid);
            }

        }

    }
}

/**
 * 读取树形数据,树形数据$data，$type 前台还是后台
 */
if (!function_exists('getTreeDataForTable')) {
    function getTreeDataForTable($data, $type = "home")
    {

        foreach ($data as $key => $val) {

            $class = '';

            if ($val["level"] == 1) {
                $class = "style='font-weight: bold;font-size: 20px;'";
            }

            $stauts = $val["stauts"] == '1' ? '启用' : '禁用';

            echo "<tr><td>" . $val["id"] . "</td>" .

                "<td " . $class . ">" . cerate_xxx($val["level"]) . $val["name"] . "</td>" .

                "<td>" . $val["path"] . "</td>" .

                "<td>" . $val["pre_icon"] . "</td>" .

                "<td>" . $val["suf_icon"] . "</td>" .

                "<td>" . $val["order"] . "</td>" .

                "<td>" . $stauts . "</td>" .


                "<td>" .
                "<a class=\"\" href=\"" . url('admin/menu/' . $type . '/edit/' . $val["id"]) . "\">编辑</a> &nbsp;&nbsp;" .
                "<a class=\"\" href=" . "#" . ">高级选项</a> &nbsp;&nbsp;" .
                "<a class=\"\" href=\"javascript:;\" onclick=\"delData(" . $val["id"] . ")\" >删除</a></td>" .
                "</tr>";

            if (isset($val["sub"])) {
                getTreeDataForTable($val["sub"], $type);
            }

        }

    }
}

/**
 * 读取树形数据,树形数据$data
 */
if (!function_exists('getTreeDataForAuthTable')) {
    function getTreeDataForAuthTable($data)
    {

        foreach ($data as $key => $val) {

            $class = '';

            if ($val["level"] == 1) {
                $class = "style='font-weight: bold;font-size: 20px;'";
            }

            echo "<tr><td>" . $val["id"] . "</td>" .

                "<td " . $class . ">" . cerate_xxx($val["level"]) . $val["name"] . "</td>" .

                "<td>" . $val["path"] . "</td>" .

                "<td>" . $val["permissions"] . "</td>" .

                "<td>" .
                "<a class=\"\" href=\"" . url('admin/menu/auth/edit/' . $val["id"]) . "\">编辑</a> &nbsp;&nbsp;" .
                "<a class=\"\" href=\"javascript:;\" onclick=\"delData(" . $val["id"] . ")\" >删除</a></td>" .
                "</tr>";

            if (isset($val["sub"])) {
                getTreeDataForAuthTable($val["sub"]);
            }

        }

    }
}

/**
 * 通过 模块的JSON文件，获得模块的名称
 * @param string $path
 * @return mixed
 */
if (!function_exists('get_module_name')) {
    function get_module_name($path = '') {
        $cloud_modules = json_decode(file_get_contents($path . '/config.json'), true);
//        $cloud_modules = json_decode(file_get_contents(base_path() . '/plugins/ThirdPartyLogin/config.json'), true);
        return empty($cloud_modules['identification']) ? '' : $cloud_modules['identification'];
    }
}

/**
 * 获取某月份的所有日期列表
 */
if (!function_exists('get_month_days')) {
    function get_month_days($time = '', $format = 'Y-m-d') {
        $time = $time != '' ? $time : time();
        //获取当前周几
        $week = date('d', $time);
        $date = [];
        for ($i = 1; $i <= date('t', $time); $i++) {
            $date[$i] = date($format, strtotime('+' . ($i - $week) . ' days', $time));
        }
        return $date;
    }
}

/**
 * 设置 月份 的格式统一
 */
if (!function_exists('set_month_format')) {
    function set_month_format($month) {
        return (string)(strlen($month) == 1 ? '0' . $month : $month);
    }
}

/**
 * 获取指定文件夹的大小
 */
if (!function_exists('get_dir_size')) {
    function get_dir_size($path, $fileseze = 0, $limit_dir = []) {
        header("content-type:text/html;charset=utf-8");
        $handler = opendir($path); //打开当前文件夹由$path指定。
        while (($filename = readdir($handler)) !== false) {
            if ($filename != "." && $filename != "..") {//文件夹文件名字为'.'和‘..’，不要对他们进行操作
                if (is_dir($path . "/" . $filename)) {// 如果读取的某个对象是文件夹，则递归
                    if (!empty($limit_dir) && !in_array($filename, $limit_dir)) continue;
                    $fileseze = get_dir_size($path . "/" . $filename, $fileseze);
                } else $fileseze += filesize($path . "/" . $filename);//文件大小
            }
        }
        @closedir($path);
        return $fileseze;
    }
}

/**
 * 字符串 "[]" 格式 转换成数组
 */
if (!function_exists('get_string_array')) {
    function get_string_array($string) {
        $data = [];
        $arr = explode(',', $string);
        $count = count($arr);
        if (!empty($arr)) {
            foreach ($arr as $k => $v) {
                if ($k == 0) {
                    $str_s = str_replace('["','',$v);
                    $data[] = str_replace('"','',$str_s);
                } else if ($k = $count-1) {
                    $str_s = str_replace('"]','',$v);
                    $data[] = str_replace('"','',$str_s);
                } else {
                    $data[] = str_replace('""','',$v);
                }
            }
        }
        return $data;
    }
}

/**
 * 获取客户端真实IP
 */
if (!function_exists('get_client_ip_info')) {
    function get_client_ip_info() {
        $ip = false;
        if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
            $ip = $_SERVER["HTTP_CLIENT_IP"];
        }
        //多重代理服务器下的客户端真实IP地址（可能伪造）,如果没有使用代理，此字段为空
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ips = explode(", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
            if ($ip) {
                array_unshift($ips, $ip);
                $ip = FALSE;
            }
            for ($i = 0; $i < count($ips); $i++) {
                if (!eregi("^(10│172.16│192.168).", $ips[$i])) {
                    $ip = $ips[$i];
                    break;
                }
            }
        }
        //客户端IP 或 最后一层代理服务器 IP
        return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
    }
}

/**
 * 客户端设备类型（Windows、Mac、ihpone、Android、Linux等）
 */
if (!function_exists('get_client_os_info')) {
    function get_client_os_info(){
        $agent = $_SERVER['HTTP_USER_AGENT'];
        if (preg_match('/win/i', $agent) && preg_match('/98/i', $agent)) {
            $os = 'Windows 98';
        } else if (preg_match('/win/i', $agent) && preg_match('/nt 6.0/i', $agent)) {
            $os = 'Windows Vista';
        } else if (preg_match('/win/i', $agent) && preg_match('/nt 6.1/i', $agent)) {
            $os = 'Windows 7';
        } else if (preg_match('/win/i', $agent) && preg_match('/nt 6.2/i', $agent)) {
            $os = 'Windows 8';
        } else if(preg_match('/win/i', $agent) && preg_match('/nt 10.0/i', $agent)) {
            $os = 'Windows 10';
        } else if (preg_match('/win/i', $agent) && preg_match('/nt 5.1/i', $agent)) {
            $os = 'Windows XP';
        } else if (preg_match('/win/i', $agent) && preg_match('/nt 5/i', $agent)) {
            $os = 'Windows 2000';
        } else if (preg_match('/win/i', $agent) && preg_match('/nt/i', $agent)) {
            $os = 'Windows NT';
        } else if (preg_match('/win/i', $agent) && preg_match('/32/i', $agent)) {
            $os = 'Windows 32';
        } else if (preg_match('/sun/i', $agent) && preg_match('/os/i', $agent)) {
            $os = 'SunOS';
        } else if (preg_match('/ibm/i', $agent) && preg_match('/os/i', $agent)) {
            $os = 'IBM OS/2';
        } else if (preg_match('/Mac/i', $agent) && preg_match('/PC/i', $agent)) {
            $os = 'Mac';
        } else if (preg_match('/PowerPC/i', $agent)) {
            $os = 'PowerPC';
        } else if (preg_match('/AIX/i', $agent)) {
            $os = 'AIX';
        } else if (preg_match('/HPUX/i', $agent)) {
            $os = 'HPUX';
        } else if (preg_match('/NetBSD/i', $agent)) {
            $os = 'NetBSD';
        } else if (preg_match('/BSD/i', $agent)) {
            $os = 'BSD';
        } else if (preg_match('/OSF1/i', $agent)) {
            $os = 'OSF1';
        } else if (preg_match('/IRIX/i', $agent)) {
            $os = 'IRIX';
        } else if (preg_match('/FreeBSD/i', $agent)) {
            $os = 'FreeBSD';
        } else if (preg_match('/teleport/i', $agent)) {
            $os = 'teleport';
        } else if (preg_match('/flashget/i', $agent)) {
            $os = 'flashget';
        } else if (preg_match('/webzip/i', $agent)) {
            $os = 'webzip';
        } else if (preg_match('/offline/i', $agent)) {
            $os = 'offline';
        } else if (preg_match('/ipod/i', $agent)) {
            $os = 'ipod';
        } else if (preg_match('/ipad/i', $agent)) {
            $os = 'ipad';
        } else if (preg_match('/iphone/i', $agent)) {
            $os = 'iphone';
        } else if (preg_match('/android/i', $agent)) {
            $os = 'Android';
        } else if (preg_match('/linux/i', $agent)) {
            $os = 'Linux';
        } else if (preg_match('/unix/i', $agent)) {
            $os = 'Unix';
        } else {
            $os = '未知操作系统';
        }
        return $os;
    }
}

/**
 * 获取errormsg文件错误码
 */
if (!function_exists('get_errormsg_code')) {
    function get_errormsg_code($code) {
        if (empty($code)) return "";
        $path = '../errormsg.ini';
        $confing = parse_ini_file($path);
        return $confing[$code];
    }
}

/**
 * 获取operatemsg文件错误码
 */
if (!function_exists('get_operatemsg_code')) {
    function get_operatemsg_code($code) {
        if (empty($code)) return "";
        $path = '../operatemsg.ini';
        $confing = parse_ini_file($path);
        return $confing[$code];
    }
}

/**
 * 记录 - 操作日志
 */
if (!function_exists('admin_operation_log')) {
    function admin_operation_log($code = "", $content = "") {
        if (empty($code) || empty($content)) {
            return false;
        }

        $name = get_operatemsg_code($code);
        $admin_id = auth('backend')->id();
        $data = [
            'admin_id' => $admin_id,
            'item_name' => $name,
            'item_content' => $content,
            'created_at' => time()
        ];
        \App\backend\models\AdminOperationAllLogModel::insertData($data);
        return true;
    }
}

/**
 * DB查询 特殊对象格式 转换成数组格式
 */
if (!function_exists('object_to_array')) {
    /**
     * @param $data array // 对象
     * @return array
     */
    function object_to_array($data) {
        return json_decode(json_encode($data), true);
    }
}
